package com.ja10.books;

import java.util.ArrayList;

import com.example.books.R;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class SearchListAdapter<T> extends BaseAdapter {
	
	private Context context = null;
	private ArrayList<T> data = null;
	private int resource = 0;
	private int mode = 0;
	
//　----------------コンストラクタ(コンテキスト、データソース、レイアウトファイルを設定)----------------
	public SearchListAdapter(Context context, ArrayList<T> data, int resource, int mode){
		this.context = context;
		this.data = data;
		this.resource = resource;
		this.mode = mode;
	}

//　----------------データ項目の個数を取得----------------
	@Override
	public int getCount() {
		return data.size();
	}

// ----------------指定された項目を取得----------------
	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

// ----------------指定された項目を識別するためのid値を取得----------------
	@Override
	public long getItemId(int position) {
		long itemId = 0;
		if(mode == 1) {
			@SuppressWarnings("unchecked")
			BookList list = ((ArrayList<BookList>)data).get(position);
			itemId = list.getId();
		}
		else if(mode == 2) {
			@SuppressWarnings("unchecked")
			RentalList list = ((ArrayList<RentalList>)data).get(position);
			itemId = list.getId();
		}
		return itemId;
	}

//　----------------リスト項目を表示するためのViewを取得----------------
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		View view = convertView;
		
		if (convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(this.context);
            view = inflater.inflate(resource, parent, false);
		}
		
		if(mode == 1) {
			BookList item = (BookList)getItem(position);
			((TextView)view.findViewById(R.id.txtTitle)).setText(item.getTitle());
			((TextView)view.findViewById(R.id.txtWriter)).setText(item.getWriter());
			((TextView)view.findViewById(R.id.txtPublisher)).setText(item.getPublisherName());
			((ImageView)view.findViewById(R.id.bookImg)).setImageBitmap(item.getPictureBmp());

		} else if(mode == 2) {
			RentalList item = (RentalList)getItem(position);
			((TextView)view.findViewById(R.id.txtTitle)).setText(item.getTitle());
			((TextView)view.findViewById(R.id.txtWriter)).setText(item.getReturnPlanDate().replaceAll("-", "/") + " 迄");
			((TextView)view.findViewById(R.id.txtWriter)).setTextColor(Color.RED);
			((TextView)view.findViewById(R.id.txtWriter)).setTextSize(12);
			((TextView)view.findViewById(R.id.txtPublisher)).setVisibility(View.GONE);
			((ImageView)view.findViewById(R.id.bookImg)).setImageBitmap(item.getPictureBmp());
		}

		return view;
	}
}
